package com.aco.fatureapp.fragments;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang3.math.NumberUtils;

import android.app.Fragment;
import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView.MultiChoiceModeListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;
import android.widget.TextView;
import android.widget.Toast;

import com.aco.fatureapp.R;
import com.aco.fatureapp.auxiliary.FaturaRetidaAdapter;
import com.aco.fatureapp.auxiliary.FaturaRetidaItem;
import com.aco.fatureapp.enums.EnumProgress;
import com.aco.fatureapp.model.printer.Billing;
import com.aco.fatureapp.printer.libs.Printer2;
import com.aco.fatureapp.service.SrvBilling;
import com.aco.fatureapp.service.SrvMetering;
import com.aco.fatureapp.service.SrvReports;
import com.aco.fatureapp.utilitary.CallAsyncTask;
import com.aco.fatureapp.utilitary.JSonHttpRequest;
import com.aco.fatureapp.utilitary.Utils;
import com.google.inject.Inject;

public class RelFaturasRetidasFragment extends Fragment {

	private TextView mBtnLoadFaturas;
	private ListView mLstFaturasRetidas;
	private LinearLayout mPnlResultado;

	private List<FaturaRetidaItem> mItensSelected;
	private List<FaturaRetidaItem> mResult;

	private FaturaRetidaAdapter mAdapter;

	private SrvReports mSrvReports;

	/*
	 * Serviço
	 */
	@Inject
	private SrvMetering mSrvMetering;

	@Inject
	private SrvBilling mSrvBilling;

	Printer2 mPrinter = new Printer2();

	/*
	 * (non-Javadoc)
	 *
	 * @see android.app.Fragment#onCreate(android.os.Bundle)
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);

		if (mSrvMetering == null) {
			mSrvMetering = new SrvMetering();
		}

		if (mSrvBilling == null) {
			mSrvBilling = new SrvBilling();
		}
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see android.app.DialogFragment#onCreateDialog(android.os.Bundle)
	 */
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View rootView = inflater.inflate(R.layout.fragment_rel_faturas_retidas,
				container, false);

		mPnlResultado = (LinearLayout) rootView.findViewById(R.id.pnlResultado);

		mBtnLoadFaturas = (TextView) rootView.findViewById(R.id.btnLoadFaturas);

		mLstFaturasRetidas = (ListView) rootView
				.findViewById(R.id.lstFaturasRetidas);

		mAdapter = new FaturaRetidaAdapter(getActivity(),
				R.layout.adapter_fatura_retida,
				new ArrayList<FaturaRetidaItem>());

		mBtnLoadFaturas.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				new RelFaturasRetidasAsyncTask().execute(new Long[] {});

			}
		});

		mLstFaturasRetidas.setAdapter(mAdapter);
		registerMultiChoiceListener();

		return rootView;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see android.app.Fragment#onCreateOptionsMenu(android.view.Menu,
	 * android.view.MenuInflater)
	 */
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		inflater.inflate(R.menu.action_bar_menu_search, menu);

		SearchManager searchManager = (SearchManager) getActivity()
				.getSystemService(Context.SEARCH_SERVICE);

		SearchView searchView = (SearchView) menu.findItem(R.id.action_search)
				.getActionView();

		searchView.setInputType(InputType.TYPE_CLASS_NUMBER);

		searchView.setSearchableInfo(searchManager
				.getSearchableInfo(getActivity().getComponentName()));

		searchView.setOnQueryTextListener(new OnQueryTextListener() {

			@Override
			public boolean onQueryTextChange(String query) {
				return true;
			}

			@Override
			public boolean onQueryTextSubmit(String query) {

				if (NumberUtils.isNumber(query)) {
					new RelFaturasRetidasAsyncTask().execute(new Long[] { Long
							.valueOf(query) });
				}
				else {
					Toast.makeText(getActivity(), "Inscrição inválida!",
							Toast.LENGTH_LONG).show();
				}

				return false;
			}

		});

		customizeSearchWidget(searchView);
	}

	/**
	 * Tratamento necessário para a implementação da Contextual Action Bar.
	 */
	private void registerMultiChoiceListener() {
		mLstFaturasRetidas
				.setMultiChoiceModeListener(new MultiChoiceModeListener() {

					private int nr = 0;

					@Override
					public boolean onPrepareActionMode(ActionMode mode,
							Menu menu) {
						return false;
					}

					@Override
					public void onDestroyActionMode(ActionMode mode) {
						mAdapter.clearSelection();
					}

					@Override
					public boolean onCreateActionMode(ActionMode mode, Menu menu) {
						nr = 0;
						MenuInflater inflater = getActivity().getMenuInflater();
						inflater.inflate(
								R.menu.action_bar_menu_rel_faturas_retidas,
								menu);

						return true;
					}

					@Override
					public boolean onActionItemClicked(ActionMode mode,
							MenuItem item) {

						switch (item.getItemId()) {
						case R.id.action_print: {
							Set<Integer> positionsSelected = mAdapter
									.getCurrentCheckedPosition();

							mItensSelected = new ArrayList<FaturaRetidaItem>();

							for (Integer position : positionsSelected) {
								mItensSelected
										.add((FaturaRetidaItem) mLstFaturasRetidas
												.getItemAtPosition(position));
							}

							nr = 0;
							mAdapter.clearSelection();
							mode.finish();

							final String macPrinter = mSrvMetering
									.getMacImpressora();

							if (macPrinter == null) {
								Utils.alert(
										getActivity(),
										"Impressora padrão não está configurada!",
										null);
								return false;
							}

							CallAsyncTask callAsyncTask = new CallAsyncTask(
									getActivity(), true);

							callAsyncTask.execute(new CallAsyncTask.Action() {

								/*
								 * (non-Javadoc)
								 *
								 * @see
								 * com.aco.fatureapp.utilitary.CallAsyncTask
								 * .Action#execute()
								 */
								@Override
								public String execute() {

									try {

										if (mItensSelected != null
												&& !mItensSelected.isEmpty()) {
											for (FaturaRetidaItem faturaRetidaItem : mItensSelected) {

												Billing billing = mSrvBilling.getFaturaImpressao(
														faturaRetidaItem
																.getInscricao(),
														null);

												Printer2.imprimirContaEmPaginas(
														macPrinter,
														billing,
														RelFaturasRetidasFragment.this
																.getActivity(),
														mPrinter,
														faturaRetidaItem
																.getInscricao(),
														null);
											}
										}

										return null;
									}
									catch (Exception ex) {

										// Fazer o tratamento here!!!.
										Log.e("Impressao_conta",
												ex.getLocalizedMessage());
										return null;
									}
								}
							});

						}
						}

						return true;
					}

					@Override
					public void onItemCheckedStateChanged(ActionMode mode,
							int position, long id, boolean checked) {
						if (checked) {
							nr++;
							mAdapter.setNewSelection(position, checked);
						}
						else {
							nr--;
							mAdapter.removeSelection(position);
						}

						mode.setTitle(nr + " Selecionado(s)");
					}
				});

		mLstFaturasRetidas.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);

		mLstFaturasRetidas
				.setOnItemLongClickListener(new OnItemLongClickListener() {

					@Override
					public boolean onItemLongClick(AdapterView<?> parent,
							View view, int position, long id) {
						mLstFaturasRetidas.setItemChecked(position,
								!mAdapter.isPositionChecked(position));

						return false;
					}
				});
	}

	/**
	 *
	 * Responsável por executar as consultas do relatório.
	 *
	 */
	public class RelFaturasRetidasAsyncTask extends
			AsyncTask<Long, Void, EnumProgress> {

		ProgressDialog mProgressDialog = null;

		@Override
		protected void onPreExecute() {
			mProgressDialog = new ProgressDialog(getActivity());
			mProgressDialog.setCanceledOnTouchOutside(false);
			mProgressDialog.setCancelable(false);

			mProgressDialog.setMessage("Buscando faturas retidas, aguarde!");

			mProgressDialog.show();
		}

		@Override
		protected EnumProgress doInBackground(Long... params) {
			try {
				mSrvReports = new SrvReports();

				if (params.length > 0) {
					Long inscricao = params[0];

					mResult = mSrvReports.getLstFaturasRetidas(inscricao);
				}
				else {
					mResult = mSrvReports.getLstFaturasRetidas();
				}

				return EnumProgress.SUCCESS;
			}
			catch (Exception e) {
				return EnumProgress.ERRO;
			}

		}

		@Override
		protected void onPostExecute(EnumProgress result) {
			switch (result) {
			case SUCCESS:
				mAdapter.clear();

				if (mResult != null && !mResult.isEmpty()) {
					mAdapter.addAll(mResult);
				}
				else {
					Utils.alert(getActivity(),
							"Nenhuma fatura retida foi encontrada.", null);
				}

				mPnlResultado.setVisibility(!mAdapter.isEmpty() ? View.VISIBLE
						: View.GONE);
				mBtnLoadFaturas.setVisibility(!mAdapter.isEmpty() ? View.GONE
						: View.VISIBLE);

				break;

			case ERRO:

				mPnlResultado.setVisibility(View.GONE);
				mBtnLoadFaturas.setVisibility(View.VISIBLE);

				Utils.alert(getActivity(), JSonHttpRequest.ERRO_GENERICO, null);
				break;
			default:
				break;
			}

			mProgressDialog.dismiss();
			super.onPostExecute(result);
		}
	}

	/**
	 *
	 * Realiza algumas modificações no estilo do widget de pesquisa.
	 *
	 * @param searchView
	 */
	private void customizeSearchWidget(SearchView searchView) {
		searchView.setQueryHint("Digite a inscrição.");

		int searchPlateId = searchView.getContext().getResources()
				.getIdentifier("android:id/search_plate", null, null);

		View searchPlate = searchView.findViewById(searchPlateId);

		if (searchPlate != null) {
			int searchTextId = searchPlate.getContext().getResources()
					.getIdentifier("android:id/search_src_text", null, null);

			TextView searchText = (TextView) searchPlate
					.findViewById(searchTextId);

			if (searchText != null) {
				searchText.setTextColor(Color.WHITE);
				searchText.setHintTextColor(Color.WHITE);
			}
		}
	}
}